#!/usr/bin/env python
#coding:utf-8

import web,twitUtil

render = web.template.render('templates/')

urls = ('/', 'index',
    '/auth','auth',
    '/api/(.*)', 'api')

class index: 
    def GET(self):   
        web.header('Content-Type','text/html; charset=utf-8', unique=True)               
        i = web.input(oauth_verifier=None)
        
        try:#callback,update token,secret           
             credentials = {}  
             f1 = open('token.txt','r')
             str1 = f1.read()
             f1.close()
             l1 = str1.split(';')
             if '0' == l1[2].replace(r'ss=',''):
                 credentials['oauth_token'] = l1[0].replace(r'ot=','')
                 credentials['oauth_token_secret'] = l1[1].replace(r'ots=','')
                 access_token = twitUtil.get_access_token(credentials,i.oauth_verifier)
                 ot = access_token['oauth_token']#update tokens
                 ots = access_token['oauth_token_secret']#update secret
                 ss = '1'
                 str2 = 'ot=' + ot + ';' + 'ots=' + ots + ';' + 'ss=' + ss
                 f2 = open('token.txt','w')
                 f2.write(str2)
                 f2.close()
             
        except Exception,e:
            pass
        return render.twittest()

class auth:
    def POST(self):
        web.header('Content-Type','text/html; charset=utf-8', unique=True)
        str1 = ''
        try:
            credentials,str1 = twitUtil.get_auth_url()

            ot = credentials['oauth_token']
            ots = credentials['oauth_token_secret']
            ss = '0'
            str2 = 'ot=' + ot + ';' + 'ots=' + ots + ';' + 'ss=' + ss
            f2 = open('token.txt','w')
            f2.write(str2)
            f2.close()
        except Exception,e:
            str1 = str1 + ' ' + str(e)           
            return '<div>' + str1 + '</div>'
        return '<a  href="' + str1 + '">' + str1 + '</a>'
        

class api:
    def apicall(self,type):
        web.header('Content-Type','text/html; charset=utf-8', unique=True)

        access_token = {}
            
        f1 = open('token.txt','r')
        str1 = f1.read()
        f1.close()
        l1 = str1.split(';')
        if '1' == l1[2].replace(r'ss=',''):
            access_token['oauth_token'] = l1[0].replace(r'ot=','')
            access_token['oauth_token_secret'] = l1[1].replace(r'ots=','')
             
        url1 = web.url()#.replace(r'/','',1)
        if url1.startswith(r'/'):
            url1 = url1.replace(r'/','',1)
        return twitUtil.MakeApiCall(access_token,url1,type,dict(web.input()))
        
    def GET(self,para):
        return self.apicall('GET')

    def POST(self,para):
        return self.apicall('POST')
            

        
app = web.application(urls, globals())
web.config.debug = False
application = app.wsgifunc()
if __name__=="__main__":
    #app.run()
    pass

